﻿transferEditor = function(record){
	/**
	 * 供应商菜单
	 */
	var storeProv = new Ext.data.Store({
		baseParams : {
			trancode : 'Provider'
		},
        proxy: new Ext.data.HttpProxy({
            url:'../'+WebServiceUrl
		}),
        reader: new Ext.data.JsonReader({root: 'root'},[
        	{name:'id',type:'int'},
            {name:'uname',type:'string'}
         ])
	});
	/**
	 * 相关部门菜单
	 */
	var storeDept = new Ext.data.Store({
		autoLoad:true,
		baseParams : {
			trancode : 'Dept'
		},
        proxy: new Ext.data.HttpProxy({
            url:'../'+WebServiceUrl
        }),
        reader: new Ext.data.JsonReader({root: 'root'},[
        	{name:'idtDept',type:'int'},
            {name:'deptName',type:'string'}
         ])
	});
	
	 storeDept.on('load', function() {
	 	if(record){			//判断打开的是不是编缉面板
    		var forms = panel.findByType('panel');
	 		forms[0].getForm().loadRecord(record);
	 		Ext.getCmp('uname').setValueField(record.data['uid']);// 重新设置hiddenValue的值
	 		Ext.getCmp('backuname').setValueField(record.data['back_uid']);
	 	}
	 })
				  
	/**
	 * 验收人菜单
	 */
	var storeTperson = new Ext.data.Store({
		baseParams : {
			trancode : 'Tperson'
		},
        proxy: new Ext.data.HttpProxy({
            url:'../'+WebServiceUrl
        }),
        reader: new Ext.data.JsonReader({root: 'root'},[
        	{name:'idt_person',type:'int'},
            {name:'pname',type:'string'}
         ])
	});
	
	
	/**
	 * 单据类型下拉框
	 */
	var kindCombo =  new Ext.form.ComboBox({
        store : new Ext.data.SimpleStore({
			fields : ["id", "kind"],
			data : [['0','普通单据'], 
					['1','从售后退回']
				]
		}),
		displayField : 'kind',
		valueField:'id',
		hiddenName:'kind',
		mode : 'local',
		minListWidth:100,
		triggerAction : 'all',
        allowBlank: false
    })
    
    var dateConv = function(v){
		if(!v)return;
		else{
			return new Date(v.time)
		}
	}
	
    //官方解决grid中combox的displyafield的显示问题
	Ext.ns("Ext.ux.renderer");  
      
	Ext.ux.renderer.ComboRenderer = function(options) {  
	    var value = options.value;  
	    var combo = options.combo;  
	  
	    var returnValue = value;  
	    var valueField = combo.valueField;  
	          
	    var idx = combo.store.findBy(function(record) {  
	       if(record.get(valueField) == value) {  
	           returnValue = record.get(combo.displayField);  
	           return true;  
	       }  
	       
		});  
		return returnValue; 
	};  
	
	Ext.ux.renderer.Combo = function(combo) {  
		return function(value, meta, record) {  
			return Ext.ux.renderer.ComboRenderer({value: value, meta: meta, record: record, combo: combo});  
		};  
	}  

	
	var sm = new Ext.grid.CheckboxSelectionModel({
		singleSelect : false
	});

    var cm = new Ext.grid.ColumnModel([sm,
		{header : '单据ID',		dataIndex :'num',	hidden:true},
		{header : '序号',			dataIndex :'ord',	hidden:true},
		{header : '物料名称ID', dataIndex : 'idt_Materiel',hidden:true}, 
		{header : '物料名称',		dataIndex :'materielName'},
		{header : '批号',			dataIndex :'batchno',
			editor:new Ext.form.TextField(),hidden:true},
		{header : '厂家条码',		dataIndex :'factcode',
			editor:new Ext.form.TextField(),hidden:true},
		{header : '机身码',			dataIndex :'serialNo',
			editor:new Ext.form.TextField(),hidden:true},
		{header : '调出库位',		dataIndex :'pgid',hidden:true},
		{header : '生产日期',		dataIndex :'prod_date',renderer : Ext.util.Format.dateRenderer('Y-m-d'),
			editor : new Ext.form.DateField({format: 'Y-m-d',allowBlank : false}),hidden:true},
		{header : '有效期',			dataIndex :'end_date',renderer : Ext.util.Format.dateRenderer('Y-m-d'),
			editor : new Ext.form.DateField({format: 'Y-m-d',allowBlank : false}),hidden:true},
		{header : '批次',			dataIndex :'batchid',
			editor:new Ext.form.TextField(),hidden:true},
		{header : '调拨数量',		dataIndex :'amount',
			editor:new Ext.form.NumberField({allowBlank : false,allowNegative : false,minValue : 1})},
		{header : '调拨价格',		dataIndex :'back_price',
			editor:new Ext.form.NumberField({allowBlank : false,allowNegative : false,minValue : 0})},
		{header : '合计',		dataIndex :'total'},
		{header : '调拨原因',		dataIndex :'cause',
			editor:new Ext.form.TextField()},
		/*{header : '单据类型',		dataIndex :'kind',		
			editor:kindCombo,	renderer:Ext.ux.renderer.Combo(kindCombo)},*/
		{header : '审核意见',		dataIndex :'aret',hidden:true},
		{header : '审核人',			dataIndex :'aname',hidden:true},
		{header : '审核日期',		dataIndex :'adate',renderer : Ext.util.Format.dateRenderer('Y-m-d'),hidden:true},
		{header : '接收库位',		dataIndex :'placeno_cs',hidden:true}
	]);
	cm.defaultSortable = true;

    var store = new Ext.data.Store({
    	proxy : new Ext.data.HttpProxy({
			url : '../' + WebServiceUrl
		}),
		reader : new Ext.data.JsonReader({
			totalProperty : 'totalProperty',
			root : 'root'
		},  
        [{name:'num'},
		{name:'ord'},
		{name:'gid'},
		{name:'batchno'},
		{name:'factcode'},
		{name:'serialNo'},
		{name:'pgid'},
		{name:'prod_date',convert:dateConv},
		{name:'end_date',convert:dateConv},
		{name:'batchid'},
		{name:'amount'},
		{name:'back_price'},
		{name:'cause'},
		{name:'aret'},
		{name:'astate'},
		{name:'kind'},
		{name:'apid'},
		{name:'adate',convert:dateConv},
		{name:'state'},
		{name:'placeno_cs'},
		{name:'idt_Materiel'},
		{name:'materielName'},
		{name:'aname'},
		{name:'total'}
		])
    });
    
    var grid = new Ext.grid.EditorGridPanel({
    	pageSize:App.pageSize,
		store: store,
		autoScroll:true,
		cm: cm,
		border:false,
		sm: sm,
		clicksToEdit : 2,
		tbar:[{
			id:'addTransfer',
			text:'增加',
			iconCls: 'add',
			disabled : record ? false : true,
			handler:function(){new selectMateriel(grid)}  
		},{
			text:'删除',
			iconCls: 'remove',
			handler:function(){
				var records = grid.getSelectionModel().getSelections();
				var isDate = false;//用来判断所选记录中是否是从数据库中取出来的
				if(records){
					var json=[];
					for(i=0,cnt=records.length;i<cnt;i++){
						if(records[i].get('num')){
							json.push(records[i].data);
							isDate = true;
						}else{
							store.remove(records[i]);
						}
					}
					if(isDate){
						Ext.Msg.confirm('确认删除','确定要从数据库中删除所选记录?',function(btn,text){
							if(btn == 'yes'){
								Ext.Ajax.request( {
									url :'../'+WebServiceUrl,
									params : {
										trancode :'61115',
										detail:Ext.encode(json)
									},
									method :'Post',
									success : function(result, request) {
										var jsonData = Ext.util.JSON.decode(result.responseText);
										if (jsonData.success) {
											Ext.MessageBox.alert('操作成功', jsonData.message);
											var records = grid.selModel.getSelections();
											for(i=0,cnt=records.length;i<cnt;i++){
												store.remove(records[i]);
											}
										} else {
											Ext.MessageBox.alert('操作失败', jsonData.message);
										}
									},
									failure : function(result, request) {
										Ext.MessageBox.alert('操作失败', '联系管理员');
									}
								});	
							}
						});
					}
				}else{
					Ext.MessageBox.alert('操作错误','请先选择一条记录');
				}
			}
        }],
		loadMask : {
			msg : '正在加载数据，请稍候。。。'
		}
    });
    var panel;
	var win;
	if(!panel){
		panel = new Ext.Panel({
			border:false,
			layout:'border',
			items:[new Ext.FormPanel({
					region:'north',
					autoHeight:true,
	            	border:false,
    				bodyStyle: "padding:5 15 0 0;", 
					labelAlign: 'right',
					items: [{
	                    layout: 'column',
	                    border:false,
	                    items: [{
	                        columnWidth:.5,
	                        layout: 'form',
	                        labelWidth:70,
	                        border:false,
							defaultType: 'combo',
	                        items: [{
	                        	xtype:'textfield',
	                            fieldLabel: '单据编号',
	                            name:'mov_no',
				    			readOnly:true,
				    			value:'自动编号',
	                            anchor: '100%'
	                        },{
	                            fieldLabel: '调拨部门',
	                            store:storeDept,
	                            id:'uname',
	                            name:'uname',
	                            displayField : 'deptName',
	                            hiddenName:'uid',
							    valueField:'idtDept',
							    mode : 'remote',
							    minListWidth:100,
							    triggerAction : 'all',
	                            allowBlank: false,
	                            editable:false, 
				    			msgTarget: 'qtip',
	                            anchor: '100%',
	                            listeners: {
							        	select : function() {
							        　　		Ext.getCmp('addTransfer').setDisabled(false);
							    	}  
							    }
	                        },{ 
	                        	xtype:'datefield',
	                        	name:'cw_date',
	                            fieldLabel: '财务日期',
	                            format: 'Y-m-d',
	                            //allowBlank:false,
	                            anchor: '100%',
	                            msgTarget: 'qtip'
	                        }]
	                    },{
	                        columnWidth: .5,
	                        layout: 'form',
	                        labelWidth:70,
	                        border:false,
	                        defaultType: 'combo',
	                        items: [{
	                        	xtype:'textfield',
	                            fieldLabel: '制单人',
	                            value:getUserName(),
	                            readOnly:true,
	                            name:'pname',
	                            anchor: '100%'
	                        },{
	                            fieldLabel: '接收部门',
	                            id:'backuname',
	                            name:'backuname',
	                            hiddenName:'back_uid',
	                            store:storeDept,
	                            displayField : 'deptName',
								valueField:'idtDept',
								//hiddenName:'idtDept',
								//emptyText:'请选择验收人部门',
								mode : 'remote',
								minListWidth:100,
								editable:false, 
								allowBlank:false,
								triggerAction : 'all',
								msgTarget: 'qtip',
	                            anchor: '100%'
	                        },{
	                        	xtype:'datefield',
	                        	name:'operdate',
	                            fieldLabel: '制单日期',
	                            disabled :true,
	                            format: 'Y-m-d',
	                            value:new Date,
	                            anchor: '100%'
	                        }]
	                    }/*,{
	                        columnWidth:.33,
	                        layout: 'form',
	                        labelWidth:70,
	                        border:false,
							defaultType: 'combo',
	                        items: []
	                    }*/]
	                }]
	    		}),{
	                region:'center',
	                layout:'fit',
	                border:false,
	                items:grid
            	}]
		});
	}
	if(!win){
		win = new Ext.Window({
                layout: 'fit',
                width: 640,
                height: 430,
                buttonAlign:'center',
                resizable: true,
                modal:true,
                plain:true,
                title: '调拨单编缉器',
                items: panel,
                buttons:[{
                	text:'保存',
                	handler : function() {
                		var forms = panel.findByType('panel');
						if (forms[0].form.isValid()) {
							var json = [];
							for(i=0,cnt=store.getCount();i<cnt;i++){
								var record = store.getAt(i);
								json.push(record.data);
							}
							if(json.length==0){
								Ext.Msg.alert('提示信息','至少一条明细信息！');
								return;
							}
							forms[0].form.submit({
								waitTitle : "请稍候",
								waitMsg : '正在保存数据...',
								url :'../'+WebServiceUrl,
								params : {trancode : '61113',detail:Ext.encode(json)},
								method : 'Post',
								failure : function() {
									Ext.MessageBox.alert('操作失败', '联系管理员');
								},
								success : function(form, action) {
									if (action.result.success=='true'){
										Ext.MessageBox.alert('操作成功',action.result.message);
										Ext.getCmp('transferRecordGrid').getStore().reload();
										win.close();
									}else{
										Ext.MessageBox.alert('操作失败',action.result.message);
									}
								}
							});
						} else {
							Ext.MessageBox.alert('输入错误', '请输完内容后再保存！');
						}
					}
                },{
                	text:'取消',
                	handler:function(){
                		win.close();
                	}
                }]
            });
    	}
    	
    	win.on('show',function(){		
    		if(record){			//判断打开的是不是编缉面板
    			var forms = panel.findByType('panel');
//    			Ext.getCmp('uname').doQuery("",true);
//    			forms[0].getForm().loadRecord(record);//自动加载数据
//    			Ext.Msg.alert(Ext.getCmp('uname').setValue(record.get('uid')));
//    			Ext.Msg.alert(Ext.getCmp('backuname'));
    			
    			this.buttons[0].setHandler(function(){		//更换点击事件
                		var forms = panel.findByType('panel');
						if (forms[0].form.isValid()) {
							var json = [];
							for(i=0,cnt=store.getCount();i<cnt;i++){
								var rec = store.getAt(i);//从ds store临时储存空间里读取值到RECORD里
								//if(record.dirty) // 得到所有修改过的数据
								json.push(rec.data);//json是一种储存格式是XML的简化版
								rec = null;
							}
							if(json.length==0){
								Ext.Msg.alert('提示信息','至少一条明细信息！');
								return;
							}
							forms[0].form.submit({
								waitTitle : "请稍候",
								waitMsg : '正在保存数据...',
								url :'../'+WebServiceUrl,
								params : {trancode : '61114',detail:Ext.encode(json),num:record.get('num')},
								method : 'Post',
								failure : function() {
									Ext.MessageBox.alert('操作失败', '联系管理员');
								},
								success : function(form, action) {
									if (action.result.success=='true'){
										Ext.MessageBox.alert('操作成功','更新成功');
										Ext.getCmp('gridDetail').getStore().reload();
										win.close();
									}else{
										Ext.MessageBox.alert('操作失败','更新失败');
									}
								}
							});
						} else {
							Ext.MessageBox.alert('输入错误', '请输完内容后再保存！');
					}
    			});
    			
    			store.baseParams={
    				num:record.get('num'),
    				trancode:'61111'
    			}
    			store.reload();
    		}
    	})
    	win.show();
//    	if(record){			//判断打开的是不是编缉面板
//    			var forms = panel.findByType('panel');
////    			Ext.getCmp('uname').store.items[0];
//    			forms[0].getForm().loadRecord(record);//自动加载数据
//    	}
}